const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const log4js = require('./utils/log4j')
const util = require('./utils/util')
const logger = require('koa-logger')
const router = require('koa-router')()
const koajwt = require('koa-jwt')

const users = require('./routes/users')
const menus = require('./routes/menus')
const roles = require('./routes/roles')
const depts = require('./routes/depts')

// error handler
onerror(app)

// db
require('./config/db')

// middlewares
app.use(
  bodyparser({
    enableTypes: ['json', 'form', 'text']
  })
)
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(
  views(__dirname + '/views', {
    extension: 'pug'
  })
)

// logger
app.use(async (ctx, next) => {
  log4js.info(
    `params: ${
      JSON.stringify(ctx.request.query) || JSON.stringify(ctx.request.body)
    }`
  )
  await next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 200
      ctx.body = util.fail('Token认证失败', util.CODE.AUTH_ERROR)
    } else {
      throw err
    }
  })
})
app.use(
  koajwt({ secret: 'aicherish' }).unless({
    path: ['/api/users/login']
  })
)
// routes
router.prefix('/api')

router.get('/demo/test', (ctx) => {
  // const token = ctx.request.headers.authorization.split(' ')[1]
  // const payload = jwt.verify(token, 'aicherish')
  ctx.body = 'payload'
})

router.use(users.routes(), users.allowedMethods())
router.use(menus.routes(), menus.allowedMethods())
router.use(roles.routes(), roles.allowedMethods())
router.use(depts.routes(), depts.allowedMethods())

app.use(router.routes(), router.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
